<!--  线 + 柱混合图 -->
<template>
  <el-card>
    <template #header>
      <div class="flex-x-between">
        <div class="flex-y-center">各保险公司销量统计</div>
      </div>
    </template>

    <div :id="id" :class="className" :style="{ height, width }" />
  </el-card>
</template>

<script setup lang="ts">
import * as echarts from 'echarts';
import { getPolicyCompanyCount } from '@/api/Nyt7PolicyInsurance/Nyt7PolicyInsurance';
import { ref } from 'vue';
const company = ref([]);
const processedData = ref([]);
// 图表对象
const chart: Ref<echarts.ECharts | null> = ref(null);

// option && myChart.setOption(option);

const props = defineProps({
  id: {
    type: String,
    default: 'StackedLine'
  },
  className: {
    type: String,
    default: ''
  },
  width: {
    type: String,
    default: '200px',
    required: true
  },
  height: {
    type: String,
    default: '200px',
    required: true
  }
});

// 窗口大小变化时，重置图表大小
const handleResize = () => {
  setTimeout(() => {
    if (chart.value) {
      chart.value.resize();
    }
  }, 100);
};



//加载保单数量
const loadPolicyCount = async () => {
  try {
    const count = await getPolicyCompanyCount();
    company.value = count.data;
    // 处理后端数据，转换为前端图表所需的格式
    processedData.value = company.value.map((item) => {
      // 返回处理后的数据
      return [item.company, item.count];
    });
    console.log(company.value);
    console.log(processedData.value);
  } catch (error) {
    console.error('Failed to fetch policy count:', error);
  }
};

// 初始化图表
onMounted(async () => {
  chart.value = markRaw(echarts.init(document.getElementById(props.id) as HTMLDivElement));
  await loadPolicyCount();

  console.log('pro', processedData.value);

  const option = {
    dataset: [
      {
        dimensions: ['company', 'count'],
        source: processedData.value
      },
      {
        transform: {
          type: 'sort',
          config: { dimension: 'count', order: 'desc' }
        }
      }
    ],
    xAxis: {
      type: 'category',
      axisLabel: { interval: 0, rotate: 10 }
    },
    yAxis: {},
    series: {
      type: 'bar',
      encode: { x: 'company', y: 'count' },
      datasetIndex: 1
    }
  };

  chart.value.setOption(option);
  console.log(option);
  window.addEventListener('resize', handleResize);


});

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
});

onActivated(() => {
  handleResize();
});
</script>
<style lang="scss" scoped></style>
